<?php
/**
 *
 * http://my.oschina.net/mingtingling/blog/98722
 * @author: LIZHEN
 * @version $Id: DbTable.php 19582 13-12-13 上午10:39 jieyin $
 * @package Model
 */

class DbTable extends ModelBase {

    //主键
    protected $_pk = 'id';

    //记录表的字段名
    protected $_tableInfo = array();

    //表的前缀
    protected $_tablePrefix = '';

    //逻辑表名，也就是没有加前缀的表名
    protected $_tableName = '';

    //表的全称
    protected $_table = '';

    public function __construct( $tableName = null ){
        parent::__construct();
        $this->_tablePrefix = C('db=>prefix');
        if(null !== $tableName) {
            $this->_tableName = $tableName;
            $this->_table = $this->_tablePrefix.$this->_tableName;
        } elseif(!empty($this->_tableName)) {
            $this->_table = $this->_tablePrefix.$this->_tableName;
        } else {
            $this->_setTable();
        }
    }

    /**
     * 设置数据库表
     * @access protected
     * @param void
     * @return void
     */
    protected function _setTable() {
        $className = get_class($this);
        $className = strtolower(substr($className,0,-5));
        $this->_tableName = $className;
        $this->_table = $this->_tablePrefix.$this->_tableName;

    }

    /**
     * 设置option的table
     * 针对select,insert,update,delete的时候
     * $option['table']没有设置的情况
     * @access protected
     * @param void
     * @return void
     */
    protected function _setOptionTable() {
        if(!isset($this->_options['table'])
            || '' === $this->_options['table']) {
            $this->_options['table'] = $this->_table;
        }

        //echo $this->_options['table'];
    }

    public function select() {
        $this->_setOptionTable();
        $this->_sqlParser->select($this->_options);
        $this->_db->prepare($this->_sqlParser->getSql());
        $this->_db->execute();
    }

    public function update($arr) {
        $this->_setOptionTable();
        $this->_sqlParser->update($arr,$this->_options);
        $this->_db->prepare($this->_sqlParser->getSql());
        $this->_db->execute();
    }

    public function insert($arr) {
        $this->_setOptionTable();
        $this->_sqlParser->insert($arr,$this->_options);
        $this->_db->prepare($this->_sqlParser->getSql());
        $this->_db->execute();
    }

    public function delete(){
        $this->_setOptionTable();
        $this->_sqlParser->delete($this->_options);
        $this->_db->prepare($this->_sqlParser->getSql());
        #$this->_db->execute();
    }

    protected function _getOne($id){
        $this->_setOptionTable();
        $this->_options['where'] = $this->_pk . '=' . $id ;
        $this->_sqlParser->select($this->_options);
        $this->_db->prepare($this->_sqlParser->getSql());
        $this->_db->execute();
        $result = $this->_db->getAllByAssocArray();

        return is_array($result) ? array_shift($result) : false;
    }

} 